package com.ikkong.biz.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.ikkong.biz.service.ParentService;
import com.ikkong.biz.service.impl.ParentServiceImpl;
import com.ikkong.system.model.Dept;
import com.jfinal.kit.StrKit;
import org.beetl.sql.ext.jfinal.Trans;

import com.fj.hiwetoptools.PinyinUtil;
import com.ikkong.biz.meta.intercept.StudentIntercept;
import com.ikkong.biz.model.Classes;
import com.ikkong.biz.model.Parent;
import com.ikkong.biz.model.Student;
import com.ikkong.biz.model.Teacher;
import com.ikkong.biz.service.AsyncWeixinService;
import com.ikkong.biz.service.StudentService;
import com.ikkong.biz.service.impl.AsyncWeixinServiceImpl;
import com.ikkong.biz.service.impl.ClassesServiceImpl;
import com.ikkong.biz.service.impl.StudentServiceImpl;
import com.ikkong.core.dao.Blade;
import com.ikkong.core.jfinal.ext.kit.JsonKit;
import com.ikkong.core.toolbox.Record;
import com.ikkong.system.controller.base.AdminBaseController;
import com.jfinal.aop.Before;
import com.jfinal.upload.UploadFile;

/**
 * Generated by Blade. 2016-11-17 15:53:59
 */
public class StudentController extends AdminBaseController {
	private static String CODE = "student";
	private static String PERFIX = "tb_student";
	private static String LIST_SOURCE = "Student.list";
	private static String BASE_PATH = "/biz/student/";

	StudentService service = new StudentServiceImpl();
	AsyncWeixinService asyncService = new AsyncWeixinServiceImpl();
    ParentService parService = new ParentServiceImpl();

	public void index() {
		setAttr("code", CODE);
		render(BASE_PATH + "student.html");
	}

	public void add() {
		setAttr("code", CODE);
		render(BASE_PATH + "student_add.html");
	}

	public void edit() {
		String id = getPara(0);
		Student student = service.findById(id);
		setAttr("model", JsonKit.toJson(student));
		setAttr("id", id);
		setAttr("code", CODE);
		render(BASE_PATH + "student_edit.html");
	}

	public void view() {
		String id = getPara(0);
		Student student = service.findById(id);
        Map<Integer,String> classesNames = new ClassesServiceImpl().allClassNames();
		student.setClass_name(classesNames.get(student.getClass_id()));
		setAttr("model", JsonKit.toJson(student));
		setAttr("id", id);
		setAttr("code", CODE);
		render(BASE_PATH + "student_view.html");
	}

	public void list() {
		Object grid = paginate(LIST_SOURCE, new StudentIntercept());
		renderJson(grid);
	}

	public void save() {
		Student student = mapping(PERFIX, Student.class);
		Student db = service.findFirstBy("mobile="+student.getMobile(), null);
		if(null !=db){
			renderJson(error("手机号已经存在,请重新输入"));
			return;
		}
		student.setVersion(0);
		student.setCtime(new Date());

		Classes classes = Blade.create(Classes.class).findById(student.getClass_id());
		student.setDept_id(classes.getStu_dept_id());
		
		boolean result = service.save(student);

		if (result) {
			renderJson(success(SAVE_SUCCESS_MSG));
		} else {
			renderJson(error(SAVE_FAIL_MSG));
		}
	}
	
	@Before(Trans.class)
	public void update() {
		Student student = mapping(PERFIX, Student.class);
        if (StrKit.isBlank(student.getMobile())){
            renderJson(error("手机号不能为空,请重新输入"));
            return;
        }
        if (student.getClass_id().intValue()<1){
            renderJson(error("班级不能为空,请重新输入"));
            return;
        }
		Student db1 = service.findFirstBy("mobile="+student.getMobile()+" and id!="+student.getId(), null);
		if(null !=db1){
            renderJson(error("手机号已经存在,请重新输入"));
            return;
        }
		student.setVersion(student.getVersion() + 1);
		Student db = service.findById(student.getId());
		db.setVersion(student.getVersion()+1);
		db.setUtime(new Date());
		db.setName(student.getName());
		db.setPosition(student.getPosition());

        // 如果存在学生手机号修改，家长的学生手机号关联也要修改
        db.setMobile(student.getMobile());
        if (!student.getMobile().equals(db.getMobile())){
            List<Parent> pars = Blade.create(Parent.class).findBy("stu_mobile=#{stu_mobile}",Record.create().set("stu_mobile",db.getMobile()));
            for (Parent par : pars) {
                par.setStu_name(student.getName());
                par.setStu_mobile(student.getMobile());
                parService.update(par);
            }
        }

        //修改了班级，必须设置新的部门ID到本记录
        db.setClass_id(student.getClass_id());
        if (student.getClass_id().intValue()!=db.getClass_id().intValue()){
            //修改dept字段
            Dept newDept = Blade.create(Dept.class).findFirstBy("class_id=#{class_id}",Record.create().set("class_id",student.getClass_id()));
            db.setDept_id(newDept.getId());
            //同时修改家长的班级
            Blade.create(Parent.class).updateBy("class_id = #{class_id}", "stu_mobile=#{stu_mobile}",
                    Record.create().set("class_id", student.getClass_id()).set("stu_mobile", student.getMobile()));
        }

        boolean temp = service.updateEveryCol(db);
        if (temp) {
			renderJson(success(UPDATE_SUCCESS_MSG));
		} else {
			renderJson(error(UPDATE_FAIL_MSG));
		}
	}

	public void remove() {
		String ids = getPara("ids");
		int cnt = service.deleteByIds(ids);
		if (cnt > 0) {
			renderJson(success(DEL_SUCCESS_MSG));
		} else {
			renderJson(error(DEL_FAIL_MSG));
		}
	}

	public void toImport() {
		setAttr("code", CODE);
		render(BASE_PATH + "student_import.html");
	}

	public void doImport() {
		
		List<UploadFile> flist = this.getFiles("/temp", 1024*1024*50);
		if(flist.size()>0){
			UploadFile uf=flist.get(0);
			String result = service.doImport(uf.getFile());
			renderJson(success(result));
		}
	}
}
